package cn.s1995.sloth.bms.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.s1995.sloth.bizs.entity.MessageTemplate;
import cn.s1995.sloth.bizs.service.MessageTemplateService;
import cn.s1995.sloth.common.core.util.R;
import cn.s1995.sloth.common.excel.annotation.ResponseExcel;
import cn.s1995.sloth.common.log.annotation.SysLog;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * 消息模板
 *
 * @author Lex
 * @date 2024-01-10 08:11:26
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/messageTemplate")
@Tag(description = "MessageTemplate", name = "消息模板管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class MessageTemplateController {

    private final MessageTemplateService messageTemplateService;

    /**
     * 获取分页
     * @param page 分页对象
     * @param req 消息模板
     * @return
     */
	@ApiOperationSupport(order = 1)
    @Operation(summary = "获取分页", description = "获取分页")
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('bizs_MessageTemplate_view')")
    public R getPage(@ParameterObject Page page, @ParameterObject MessageTemplate req) {
        return R.ok(messageTemplateService.page(page, buildQueryWrapper(req)));
    }

    /**
     * 获取列表
     * @param req 消息模板
     * @return
     */
	@ApiOperationSupport(order = 1)
    @Operation(summary = "获取列表", description = "获取列表")
    @GetMapping("/list")
    @PreAuthorize("@pms.hasPermission('bizs_MessageTemplate_view')")
    public R getList(@ParameterObject MessageTemplate req) {
        return R.ok(messageTemplateService.list(buildQueryWrapper(req)));
    }

    /**
     * 获取对象
     * @param id id
     * @return R
     */
	@ApiOperationSupport(order = 1)
    @Operation(summary = "获取对象", description = "通过id查询")
    @GetMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('bizs_MessageTemplate_view')")
    public R getById(@PathVariable("id" ) Long id) {
        return R.ok(messageTemplateService.getById(id));
    }

    /**
     * 新增消息模板
     * @param req 消息模板
     * @return R
     */
	@ApiOperationSupport(order = 10)
    @Operation(summary = "新增消息模板", description = "新增消息模板")
    @SysLog("新增消息模板")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('bizs_MessageTemplate_add')")
    public R save(@RequestBody MessageTemplate req) {
        return R.ok(messageTemplateService.save(req));
    }

    /**
     * 修改消息模板
     * @param req 消息模板
     * @return R
     */
	@ApiOperationSupport(order = 20)
    @Operation(summary = "修改消息模板", description = "修改消息模板")
    @SysLog("修改消息模板")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('bizs_MessageTemplate_edit')")
    public R updateById(@RequestBody MessageTemplate req) {
        messageTemplateService.updateById(req);
        messageTemplateService.removeCacheMessageTemplate(req.getId());
        return R.ok();
    }

    /**
     * 通过id删除消息模板
     * @param ids id列表
     * @return R
     */
	@ApiOperationSupport(order = 30)
    @Operation(summary = "通过id删除消息模板", description = "通过id删除消息模板")
    @SysLog("通过id删除消息模板")
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('bizs_MessageTemplate_del')")
    public R remove(@RequestBody Long[] ids) {
        messageTemplateService.removeBatchByIds(CollUtil.toList(ids));
        for (Long id : ids) {
            messageTemplateService.removeCacheMessageTemplate(id);
        }
        return R.ok();
    }

    /**
     * 导出excel 表格
     * @param req 查询条件
   	 * @param ids 导出指定ID
     * @return excel 文件流
     */
	@ApiOperationSupport(order = 40)
    @Operation(summary = "导出excel表格", description = "")
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('bizs_MessageTemplate_export')")
    public List<MessageTemplate> export(MessageTemplate req, Long[] ids) {
        return messageTemplateService.list(Wrappers.lambdaQuery(req).in(ArrayUtil.isNotEmpty(ids), MessageTemplate::getId, ids));
    }

    @NotNull
    private static LambdaQueryWrapper<MessageTemplate> buildQueryWrapper(MessageTemplate req) {
        LambdaQueryWrapper<MessageTemplate> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Objects.nonNull(req.getId()), MessageTemplate::getId, req.getId());
        wrapper.eq(Objects.nonNull(req.getType()), MessageTemplate::getType, req.getType());
        wrapper.eq(Objects.nonNull(req.getState()), MessageTemplate::getState, req.getState());

        wrapper.and(
                StrUtil.isNotEmpty(req.getSearch()),
                w -> w.like(MessageTemplate::getId, req.getSearch())
                        .or()
                        .like(MessageTemplate::getTitle, req.getSearch())
                        .or()
                        .like(MessageTemplate::getContent, req.getSearch())
        );
        return wrapper;
    }

}
